package threading;

import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Microsoft
 * Date: 2023-07-15
 * Time: 16:15
 */
//表示一个任务
class MyTask implements Comparable<MyTask>{
    public Runnable runnable;
    public long time;


    public MyTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        //取当前时刻的时间戳+delay，作为该任务实际执行的时间戳
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTask o) {
        //表示每次取出的是时间最小的
        return (int)(this.time - o.time);
    }
}

class MyTimer {
    //这个结构，是带有优先级的阻塞队列，核心数据结构
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();


    //创建一个锁对象
    private Object locker = new Object();

    //此处的delay是一个形如3000这样的数字（多长时间后，执行该任务）
    public void schedule (Runnable runnable,long delay) {
        //根据参数构造MyTask，插入队列
        MyTask myTask = new MyTask(runnable,delay);
        queue.put(myTask);//插入队列
        synchronized (locker) {
            locker.notify();
        }
    }

    //构造线程，负责执行具体任务
    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {//wait是要搭配suo来使用
                        MyTask myTask = queue.take();
                        long curentTime = System.currentTimeMillis();
                        if (myTask.time <= curentTime) {
                            //时间到了，可以执行任务了
                            myTask.runnable.run();
                        }else {
                            //时间还没到
                            //把刚才取出的任务，重新塞回队列中
                            queue.put(myTask);
                            locker.wait(myTask.time-curentTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class ThreadDemo23 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello4");
            }
        },4000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello2");
            }
        },2000);

    }
}
